import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Modal, Form, Spin, Select, Button, message } from 'antd'
import { ChooseAccountInput } from '@/desktop/components/ChooseAccount'
import services from '@/services'
import type { BaseAccount } from '@/services/auth'
import type { ExternalItemTag } from '@/services/contact-types/'
import type { AutoTransferRule } from '@/services/features/auto-transfer'
import type { AccountQywx } from '@/services/qywxs'
import './Edit.module.less'

export default function EditRule(props: {
  visible: boolean
  rule: AutoTransferRule | null
  rules: AutoTransferRule[]
  onFinish: () => void
}) {
  const { visible, rule, rules, onFinish } = props
  if (!visible) return null

  return <Modal
    styleName="modal"
    width="50vw"
    title={rule === null ? '新建转交规则' : '编辑转交规则'}
    footer={null}
    open={visible}
    destroyOnClose
    maskClosable={false}
    onCancel={onFinish}
  >
    <Content rule={rule} rules={rules} onFinish={onFinish} />
  </Modal>
}

interface FormValues {
  tags: string[]
  accounts: string[]
  wxids: string[]
}
const emptyForm: FormValues = { tags: [], accounts: [], wxids: [] }

function Content(props: {
  rule: AutoTransferRule | null
  rules: AutoTransferRule[]
  onFinish: () => void
}) {
  const { rule, rules, onFinish } = props

  const usedTags = useMemo(() => {
    const set = new Set<string>()
    rules.forEach(r => {
      if (r.id === rule?.id) return
      r.tags.forEach(tag => set.add(tag.id))
    })
    return set
  }, [rule, rules])

  const [qywxs, setQywxs] = useState<AccountQywx[] | null>(null)
  const [tags, setTags] = useState<ExternalItemTag[] | null>(null)
  const [accounts, setAccounts] = useState<BaseAccount[] | null>(null)
  useAsyncEffect(async () => {
    const { qywxs: _qywxs, accounts: _accounts } = await services.qywxs.getAllAccountQywxs()
    setQywxs(_qywxs)
    setAccounts(_accounts)

    const corpIds = [...new Set(_qywxs.map(v => v.corpid))]
    const res = await services.externals.tags.getCorpTags(corpIds)
    setTags(res.success ? res.data : [])
  }, [])

  const initialValues = useMemo(() => {
    return rule && qywxs && tags && accounts
      ? {
          tags: rule.tags.map(v => v.id).filter(id => tags.find(v => v.id === id)),
          accounts: rule.accounts.map(v => v.id).filter(id => accounts.find(v => v.id === id)),
          wxids: rule.wxids.filter(wxid => qywxs.find(v => v.wxid === wxid)),
        }
      : { ...emptyForm }
  }, [rule, qywxs, tags, accounts])

  const [saving, setSaving] = useState(false)
  const submit = useCallback(
    async (values: FormValues) => {
      if (!tags || !accounts) return
      setSaving(true)

      const id = rule ? rule.id : undefined
      const enable = rule ? rule.enable : true
      const result = await services.features.autoTransfer.addOrUpdateRule({
        id,
        enable,
        tags: values.tags
          .map(_id => tags.find(v => v.id === _id))
          .filter((v): v is ExternalItemTag => !!v)
          .map(tag => ({ id: tag.id, name: tag.name })),
        accounts: values.accounts
          .map(_id => accounts.find(v => v.id === _id))
          .filter((v): v is BaseAccount => !!v)
          .map(v => ({ id: v.id, name: v.name })),
        wxids: values.wxids,
      })
      setSaving(false)
      if (result === true) {
        setTimeout(() => void services.transfers.load(), 500) // 保存转交规则时会立刻执行一次，因此要刷新一下转交列表
        onFinish()
      } else {
        void message.warning(`保存失败，${result}`)
      }
    },
    [rule, tags, accounts, onFinish],
  )

  if (!qywxs || !tags || !accounts) {
    return <div styleName="loading">
      <Spin size="large" tip="加载中..." />
    </div>
  }

  return <Form initialValues={initialValues} styleName="form" onFinish={submit}>
    <div styleName="body">
      <Form.Item
        name="tags"
        rules={[{ required: true, message: '请选择要转交的客户标签' }]}
        label="要转交的客户标签"
        extra="具有选中标签的客户将被自动进行转交，可多选"
      >
        <Select
          mode="multiple"
          placeholder="选择客户标签"
          style={{ width: '100%' }}
          options={tags.map(tag => ({
            label: tag.name,
            value: tag.id,
            disabled: usedTags.has(tag.id),
          }))}
          optionFilterProp="label"
        />
      </Form.Item>
      <Form.Item
        name="accounts"
        rules={[{ required: true, message: '请选择接收转交的账号' }]}
        label="接收转交的账号"
        extra="选中的账号将接收转交"
      >
        <ChooseAccountInput multiple={true} />
      </Form.Item>
      <Form.Item
        name="wxids"
        rules={[{ required: true, message: '请指定生效范围' }]}
        label="规则生效范围"
        extra="此条转交规则将自动应用于选中的企业微信"
      >
        <Select mode="multiple" placeholder="选择生效的企业微信" style={{ width: '100%' }}>
          {qywxs.map(qywx => <Select.Option
            key={qywx.wxid}
            value={qywx.wxid}
            title={qywx.friendlyName}
          >
            {qywx.friendlyName}
          </Select.Option>)}
        </Select>
      </Form.Item>
    </div>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" htmlType="submit" loading={saving}>
        {rule ? '保存' : '创建'}
      </Button>
    </footer>
  </Form>
}
